const static = require("node-static");
const http = require("http");
const file = new static.Server();
const app = http
  .createServer(function (req, res) {
    file.serve(req, res);
  })
  .listen(2013);
const io = require("socket.io")(app, {
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
}); //侦听 2013
console.log(`LJ - socket.io 服务启动成功...`);
io.sockets.on("connection", (socket) => {
  function log() {
    const array = [">>> Message from server: "];
    for (var i = 0; i < arguments.length; i++) {
      array.push(arguments[i]);
    }
    socket.emit("log", array);
  }

  socket.on("message", (message) => {
    console.log("LJ - 收到消息:", message);
  });

  socket.on("create or join", (room) => {
    //收到 “create or join” 消息
    var clientsInRoom = io.sockets.adapter.rooms[room];
    var numClients = clientsInRoom
      ? Object.keys(clientsInRoom.sockets).length
      : 0; //房间里的人数

    console.log(`LJ - 房间[${room}]当前客户端数量[${numClients}]`);

    // 给房间人员推送加入房间消息
    io.sockets.in(room).emit("join", room);
    // 加入房间
    socket.join(room);

    if (numClients > 100) {
      // 人员过多发送，full消息
      socket.emit("full", room);
    }

    console.log(`LJ - 房间[${room}]：客户端[${socket.id}]进入`);
  });
});
